
import base_class
import inspect
import sys,os
import paho.mqtt.client as mqtt
class mqtt_class(base_class.base_class):
    def __on_connect(self,client, userdata, flags, rc):
        if rc == 0:
            print("Connected to MQTT broker")
            client.subscribe("topic1")
        else:
            print("Failed to connect, return code %d\n", rc)
    def __on_message(self,client, userdata, message):
        print(message.topic,{str(message.payload.decode('utf-8'))})

    def create_obj(self):
        try:
            #检查目标服务是否启动
            self.send_message(message="A")
        except:
            print("?????????????????????????")
            py_file_path=self.project_dir_path+os.sep+self.temp_name+".py"
            log_file_path=self.project_dir_path+os.sep+self.temp_name+".log"
            print(py_file_path,'\n',log_file_path)
            #创建进程
            with open(py_file_path,'w',encoding="utf-8") as f:
                str_="""
import base_class
import inspect
import sys,os
import paho.mqtt.client as mqtt
"""+self._getsource()+f"""
if __name__=="__main__":
    obj=mqtt_class(**{self.kwargs})
    import time
    print(time.time(),"runserver")
    obj.run_server()
"""
                f.write(str_)
            self._create_process(py_file_path,log_file_path)
        return self.recv_port
    def _add_topic(self,**kwargs):
        pass
    def init(self,**kwargs):
        self.broker_address=kwargs.get("broker_address")
        self.broker_port=kwargs.get("broker_port")
    def run_server(self):
        print("start server")
        # 创建 MQTT 客户端实例
        client = mqtt.Client()
        # 连接到 MQTT 服务器
        client.connect(self.broker_address, self.broker_port)
        # 开始循环监听
        client.loop_start()
        #与其他进程进行通信的socket服务（用于接收数据
        self._recv()

if __name__=="__main__":
    import ctypes  
  
    obj=mqtt_class(**{'broker_address': '127.0.0.1', 'broker_port': 1883, 'project_dir_path': 'E:\\my\\easy_edit\\_base_tool\\python', 'recv_port': 5555, 'process_id': None, 'temp_name': 'mqtt_test'})
    import time
    print(time.time(),"runserver")
    obj.run_server()
